function history(id) {

    layer.open({
        title: "历史记录",
        shade: 0.5,
        type: 1,
        skin: 'layui-layer-molv',
        area: ['700px', '450px'],
        btn: ['确定'],
        content: '<div style="padding: 10px;"> <table id="jqGrids"></table><div id="jqGridPagers"></div></div>',
        success: function (layero, index) {

            $("#jqGrids").jqGrid({
                url: baseURL + 'sys/tianansubmit/list?tianid=' + id,
                datatype: "json",
                colModel: [
                    {label: '部门负责人审核留言', name: 'rescause', index: 'rescause', width: 80},
                    {label: '部门负责人审核时间', name: 'restime', index: 'restime', width: 80},
                    {label: '院领导审核留言', name: 'leacause', index: 'leacause', width: 80},
                    {label: '院领导审核时间', name: 'ledtime', index: 'ledtime', width: 80},
                ],
                viewrecords: true,
                height: 300,
                rowNum: 8,
                rowList: [10, 30, 50],
                rownumbers: true,
                rownumWidth: 25,
                autowidth: true,
                multiselect: true,
                pager: "#jqGridPagers",
                jsonReader: {
                    root: "page.list",
                    page: "page.currPage",
                    total: "page.totalPage",
                    records: "page.totalCount"
                },
                prmNames: {
                    page: "page",
                    rows: "limit",
                    order: "order"
                },
                gridComplete: function () {
                    //隐藏grid底部滚动条
                    $("#jqGrids").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
                }
            });

        },
        //确认回调
        btn1: function () {

            layer.closeAll()
        },


    });


}

var curFiles = [];
var downUrl = [];
var title;

function infos(id) {
    var tianan;
    $.ajax({
        type: "GET",
        url: baseURL + "../sys/tianan/info/" + id,
        success: function (r) {
            tianan = r.tianan;
            layer.open({
                title: tianan.title,
                type: 1,
                skin: 'layui-layer-molv',
                area: ['800px', '450px'],
                content: '<div class="row" style="padding: 10px">' +
                    ' <table class="table table-bordered table-style"> ' +
                    ' <tbody class="tablebody"> ' +
                    '<tr><td style="width:110px; ">提案人</td><td style="    width: 180px;">' + tianan.creatusername + '</td><td style="width:85px;text-align: center; ">提案类别</td><td>' + isnull(tianan.typesName) + '</td><td style="width:120px; ">所在部门</td><td style="width:120px; ">' + isnull(tianan.deptIdName) + '</td></tr>' +
                    '<tr><td>案由分析</td><td colspan="5">' + isnull(tianan.anyoufenxi) + '</td></tr>' +
                    '<tr><td>措施建议</td><td colspan="5">' + isnull(tianan.cuoshijianyi) + '</td></tr>' +
                    '<tr><td>办理时限</td><td >' + isnull(tianan.endtime) + '</td><td style="width:85px;text-align: center;">办理类型</td><td>' + liantype(tianan.liantype) + '</td><td style="width:85px;text-align: center; ">办理部门</td><td>' + tianan.liandeptname + '</td></tr>' +
                    '<tr><td>提案类型</td><td >' + isnull(tianleibie(tianan.type)) + '</td><td style="width:85px;text-align: center;">办理状态</td><td>' + checkstatus(tianan.banjiestatus) + '</td><td style="width:85px;text-align: center; ">满意度</td><td>' + manyistatus(tianan.manyi) + '</td></tr>' +
                    '<tr><td>提案答复</td><td colspan="5">' + isnull(tianan.subexplain) + '</td></tr>' +
                    ' </tbody> ' +
                    '</table>' +
                    '<div class="input-group ">相关附件：<ul id="ulli"></ul></div>' +
                    ' </div>',
                success: function (layero, index) {
                    if (tianan.subfile != null && tianan.subfile != '') {
                        var s = [];
                        s = tianan.subfile.split(",");
                        //遍历所有文件
                        for (var i = 0; i < s.length; i++) {
                            if (s[i] != null && s[i] != 'null') {
                                s[i].replace("/", "\\")
                            }
                            var fileNameIndex = s[i].lastIndexOf("\\");
                            var filePathName = s[i].substring(fileNameIndex + 1);
                            var html = filePathName;
                            downUrl.push(s[i]);

                            html = '<li>' +
                                html + '<a class="operation_type" style="color: #0c74c4; text-decoration:none" href="../../../sys/file/fileDown?fileDir=' + encodeURIComponent(s[i]) + '"  > &nbsp;&nbsp;下载</a>'
                                + "<a class='operation_type'  style='color: #0c74c4;  border:none;text-decoration:none'   onclick='eye( \"" + s[i].replace(/\\/g, "//") + "\")' href='javascript:;'  > &nbsp;&nbsp;预览</a></li>";
                            $("#ulli").append(html);
                        }
                    } else {
                        $("#ulli").append("<p>无</p>");
                    }


                    $.ajax({
                        type: "GET",
                        url: baseURL + 'sys/tianansubmit/list?tianid=' + id,
                        success: function (r) {
                            if (r.page != null) {
                                if (r.page.list.length > 0) {

                                    for (var i = 0; i < r.page.list.length; i++) {
                                        if (r.page.list[i].banjiestatus == 4 || r.page.list[i].banjiestatus == -3) {
                                            if (r.page.list[i].banjiestatus == 4) {
                                                $(".tablebody").append('<tr><td style="color: green"> 部门负责人审核通过</td><td  colspan="3">' + r.page.list[i].rescause + '</td><td style="width:85px;text-align: center;">部门负责人审核时间</td><td>' + r.page.list[i].restime + '</td></tr>');
                                            } else {
                                                $(".tablebody").append('<tr><td style="color: red">部门负责人审核不通过</td><td  colspan="3">' + r.page.list[i].rescause + '</td><td style="width:85px;text-align: center;">部门负责人审核时间</td><td>' + r.page.list[i].restime + '</td></tr>');
                                            }
                                        }

                                        if (r.page.list[i].banjiestatus == 5 || r.page.list[i].banjiestatus == -4) {
                                            $(".tablebody").append('<tr><td style="color: green"> 部门负责人审核通过</td><td  colspan="3">' + r.page.list[i].rescause + '</td><td style="width:85px;text-align: center;">部门负责人审核时间</td><td>' + r.page.list[i].restime + '</td></tr>');
                                            if (r.page.list[i].banjiestatus == 5) {
                                                $(".tablebody").append('<tr><td  style="color: green"> 分管院领导审核通过</td><td  colspan="3">' + r.page.list[i].leacause + '</td><td style="width:85px;text-align: center;">部门领导审核时间</td><td>' + r.page.list[i].ledtime + '</td></tr>');
                                            } else {
                                                $(".tablebody").append('<tr><td style="color: red">分管院领导审核不通过</td><td  colspan="3">' + r.page.list[i].leacause + '</td><td style="width:85px;text-align: center;">分管院领导审核时间</td><td>' + r.page.list[i].ledtime + '</td></tr>');
                                            }
                                        }
                                    }
                                }
                            }

                        }

                    })
                }
            })
        }
    })
}

/**
 * 点击选择文件调用
 * 将数据存入数组
 * 上传的时候遍历数组存入formData
 * @type {number}
 */
var curFiles = [];
var downUrl = [];
var title;

function Picker() {
    var temp = document.getElementById('ul');
    var temp1 = document.getElementById('ulli');
    var linum = temp.getElementsByTagName("li").length;
    var linum2 = temp1.getElementsByTagName("li").length;
    linum = linum + linum2;
    if (linum < 15) {
        var path = $("#upFile").val();
        var input = document.getElementById("upFile");
        var f = input.files[0];
        if (path != "") {
            var pathNum = path.lastIndexOf(".");
            if (".jpg" === path.substring(pathNum).toLowerCase() || ".png" === path.substring(pathNum).toLowerCase() || ".gif" === path.substring(pathNum).toLowerCase() || ".jpeg" === path.substring(pathNum).toLowerCase()) {
                if (f.size >= 1048576) {
                    return alert("图片不能超过1M")
                }
            }
            if (f.size > 104857600) {
                return alert("上传文件大小不能超过100M")
            }
            if (".doc" != path.substring(pathNum).toLowerCase() && ".docx" != path.substring(pathNum).toLowerCase()
                && ".pdf" != path.substring(pathNum).toLowerCase() && ".xls" != path.substring(pathNum).toLowerCase()
                && ".xlsx" != path.substring(pathNum).toLowerCase() && ".ppt" != path.substring(pathNum).toLowerCase()
                && ".pptx" != path.substring(pathNum).toLowerCase()
                && ".jpg" != path.substring(pathNum).toLowerCase()
                && ".png" != path.substring(pathNum).toLowerCase()
                && ".gif" != path.substring(pathNum).toLowerCase()
                && ".jpeg" != path.substring(pathNum).toLowerCase()) {
                return alert("只能选择doc、docx、pdf、xls、xlsx、ppt、pptx、jpg、png、gif、jpeg文件");
            } else {


                $("#fileLable1").css("display", "inline");
                var fileArr = $("#upFile")[0].files[0];
                curFiles.push(fileArr);
                var j = curFiles.length - 1;
                var html = "<li id='qqq" + j + "'>" + fileArr.name + '&nbsp;&nbsp;<i class="iconfont icon-cancel" onclick=del(' + j + ') >' + '</i>' + "</li>";
                $("#ul").append(html);
            }
        }
    } else {
        return alert("上传的文件限15个")
    }
    var html = "<p style='color: green'>提交文件数:" + (linum + 1) + "个文件 <p style='color: red'>剩余提交:" + (15 - (linum + 1)) + "个文件</p></p>"
    $("#span").html(html)

}

/**
 * 根据ID删除
 * 并且删除存入数组的元素
 * @param j
 */
function del(j) {
    var temp = document.getElementById('ul');
    var linum = temp.getElementsByTagName("li").length;
    if (linum == 1) {//删除完隐藏标签
        $("#fileLable1").css("display", "none");
    }
    $("#qqq" + j + "").remove();
    curFiles.splice(j, 1, '')
}

/**
 * 文件提交
 * @param id
 */
var sfile = [];

function submit(id) {
    $.get(baseURL + "sys/tianan/info/" + id, function (r) {
        vm.tianan = r.tianan;

        var content = '<form id="test"><div id="test1" style="padding:10px 10px  0 10px">' +
            '<div class="form-group  " style="text-align: center;" > 案由分析</div>' +
            '<div class="form-group wenzi anyoufenxi" style="margin-top: 10px;border: 1px #999 solid;"></div>' +
            '<div class="form-group " style="text-align: center;" > 措施建议</div>' +
            '<div class="form-group wenzi  cuoshijianyi" style="margin-top: 10px;border: 1px #999 solid;"></div>' +
            '<div class=" wenzi renyuan" style=""></div>' +
            '<div class="form-group " style="text-align: center;" > 答复内容</div>' +
            '<div class="form-group"><div id="commitRemark"></div></div>' +
            '<div class="input-group "><label id="fileLable">原文件为：</label>' +
            '<ul id="ulli">' +
            '</ul>' +
            '</div>' +
            '<div class="form-group">' +
            '  <input type="file"  onchange="Picker()" accept="image/gif,image/jpeg,image/png,application/vnd.ms-powerpoint,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" ' +
            ' class="test" id="upFile"  value="选择文件"/>' +
            '<div ><label id="fileLable1" style="display:none;">待提交文件：<span id="span"></span></label>' +
            '<ul id="ul"></ul></div></div>' +
            '</div></form>';
        layer.open({
            title: vm.tianan.title,
            shade: 0.5,
            type: 1,
            skin: 'layui-layer-molv',
            area: ['800px', '450px'],
            btn: ['提交'],
            content: content,
            success: function () {
                $(".renyuan").html("<p>提案人：" + vm.tianan.creatusername + "&nbsp;&nbsp;&nbsp;所属部门：" + vm.tianan.deptIdName + "</p>")
                var E = window.wangEditor;
                vm.editor = new E('#commitRemark');
                vm.editor.config.menus = [];
                vm.editor.create();
                vm.editor.txt.html(vm.tianan.subexplain);
                $(".anyoufenxi").html("<p>" + vm.tianan.anyoufenxi + "</p>");
                $(".cuoshijianyi").html("<p>" + vm.tianan.cuoshijianyi + "</p>");
                sfile = [];

                if (vm.tianan.subfile) {
                    var s = [];
                    s = vm.tianan.subfile.split(",");
                    sfile = s;
                    //遍历所有文件
                    for (var i = 0; i < s.length; i++) {
                        if (s[i] != null && s[i] != 'null') {

                            s[i].replace("/", "\\")
                        }
                        var fileNameIndex = s[i].lastIndexOf("\\");
                        var filePathName = s[i].substring(fileNameIndex + 1);
                        var html = filePathName;
                        downUrl.push(s[i]);
                        html = '<li id="sss' + i + '">' +
                            html + '<a class="operation_type" style="color: #0c74c4; ' +
                            'text-decoration:none" href="../../../sys/file/fileDown?fileDir=' + encodeURIComponent(s[i]) + '"  > ' +
                            '&nbsp;&nbsp;下载</a>' +
                            "<a class='operation_type'  style='color: #0c74c4;  border:none;text-decoration:none'   onclick='eye( \"" + s[i].replace(/\\/g, "//") + "\")' href='javascript:;'  > &nbsp;&nbsp;预览</a>"
                            + '&nbsp;&nbsp;&nbsp;&nbsp;<i class="iconfont icon-cancel" style="cursor:pointer;color: red;" onclick=dels("' + i + '")>删除 </i>' +
                            '</li>';
                        $("#ulli").append(html);
                    }
                } else {
                    $("#fileLable").remove();
                }


                $("#compPercent").val(vm.tianan.subfile);


            },

            //确认回调
            btn1: function () {
                if (vm.editor.txt.html().length == 0) {
                    alert("答复不能为空");
                }

                if (curFiles.length > 15) {
                    alert("不能上传超过15个文件");
                } else {
                    //上传文件
                    submitdata();
                    vm.saveOrUpdate();
                    layer.closeAll()

                }
            },


        });
    });
}

function isnull(data) {

    if (!data) {
        return "(无)"
    } else {
        return data;
    }
}

/**
 * 文件提交
 */
function submitdata() {

    var formData = new FormData($('#form')[0]);
    for (var i = 0, j = curFiles.length; i < j; ++i) {
        if (curFiles[i] != null) {
            formData.append('files', curFiles[i]);
        }
    }
    var ss = "";
    for (var i = 0; i < sfile.length; i++) {
        if (sfile[i] !== "") {
            if (ss === "") {
                ss = sfile[i]
            } else {
                ss = ss + "," + sfile[i]
            }
        }
    }
    if (curFiles.length !== 0) {
        layer.msg("开始上传文件", {icon: 1});
        $.ajax({
            type: "POST",
            url: baseURL + "/sys/file/upload",
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (r) {
                var info = r.msg;
                //var name = info.substr(info.lastIndexOf("/") + 1);
                if (ss === "" && info !== "") {
                    vm.tianan.subfile = info;
                } else if (ss !== "" && info !== "") {
                    vm.tianan.subfile = ss + "," + info;
                } else if (ss !== "" && info === "") {
                    vm.tianan.subfile = ss;
                }
            }
        });
    } else {
        vm.tianan.subfile = ss
    }
    curFiles = [];
    downUrl = [];

    vm.tianan.subexplain = vm.editor.txt.html();

    vm.tianan.banjiestatus = "3";
};

/**
 * 删除已存在的文件
 * @param i
 */
function dels(i) {

    sfile.splice(i, 1, '');

    $("#sss" + i + "").css("display", "none");
}

function init() {

    $("#jqGridtable").html("");
    $("#jqGridtable").html('<table id="jqGrid"></table><div id="jqGridPager"></div>');
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/tianan/listbanli?sea=' + $("#sea").val() + '&banjiestatus=' + $("#banjiestatus").val(),
        datatype: "json",
        colModel: [
            {label: '提案名称', name: 'title', index: 'title', width: 60},
            {
                label: '立案类型',
                align: 'center',
                sortable: true,
                name: 'liantype',
                index: 'liantype',
                width: 40,
                formatter: function (value, row, rowObject) {

                    return lian(value);
                }
            },
            {
                label: '办理时限',
                name: 'endtime',
                index: 'endtime',
                align: 'center',
                width: 40,
            }, {
                label: '标签',
                align: 'center',
                sortable: true,
                name: 'lable',
                index: 'lable',
                width: 40,
            },
            {
                label: '状态',

                name: 'banjiestatus',
                index: 'banjiestatus',
                align: 'center',
                width: 40,
                formatter: function (value, row, rowObject) {
                    return checkstatus('' + value);
                }
            },
            {label: '提案人', align: 'center', sortable: true, name: 'creatusername', index: 'dept_id', width: 40},
            {
                label: '操作',
                name: 'id',
                align: 'center',
                index: 'id',
                width: 40,
                formatter: function (value, row, rowObject) {
                    var but = "";
                    but += ' <button type="button" class="layui-btn layui-btn-xs layui-btn-normal" onclick="infos(' + value + ')">详情</button>';
                    if (rowObject.banjiestatus == 2 || rowObject.banjiestatus == -3 || rowObject.banjiestatus == -4) {
                        but += '<button type="button" class="layui-btn layui-btn-xs layui-btn-normal" onclick="submit(' + value + ')">答复</button>';
                    }
                    return but;
                }
            }


        ],
        viewrecords: true,
        height: 360,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
}

$(function () {
    init();
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        tiananShenyi: {},
        tianan: {},
        editor: '',

    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.tiananShenyi = {};
        },
        update: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id)
        },
        saveOrUpdate: function (event) {
            var url = "sys/tianan/updatesubmit";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.tianan),
                success: function (r) {
                    if (r.code === 0) {
                        layer.msg("操作成功", {icon: 1});
                        vm.reload();

                    } else {
                        layer.alert(r.msg);

                    }
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }
            var lock = false;
            layer.confirm('确定要删除选中的记录？', {
                btn: ['确定', '取消'] //按钮
            }, function () {
                if (!lock) {
                    lock = true;
                    $.ajax({
                        type: "POST",
                        url: baseURL + "sys/tiananshenyi/delete",
                        contentType: "application/json",
                        data: JSON.stringify(ids),
                        success: function (r) {
                            if (r.code == 0) {
                                layer.msg("操作成功", {icon: 1});
                                $("#jqGrid").trigger("reloadGrid");
                            } else {
                                layer.alert(r.msg);
                            }
                        }
                    });
                }
            }, function () {
            });
        },
        getInfo: function (id) {
            $.get(baseURL + "sys/tiananshenyi/info/" + id, function (r) {
                vm.tiananShenyi = r.tiananShenyi;
            });
        },
        gettiananInfo: function (id) {

        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                page: page
            }).trigger("reloadGrid");
        }
    }
});